<!doctype html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>天天生鲜-首页</title>
<link rel="short icon" href="images/logo.png">
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/index.css">
<link rel="stylesheet" href="css/foot.css">
</head>
<style>

</style>
<body>
<div  id="yc-index">
	<!-- 头部  -->
	<div class="header_con">
    	<div class="header">
    		<div class="welcome fl">欢迎来到天天生鲜</div>
    		<div class="fr">
            	<div class="login_info fl" v-if="onlogin">
                	欢迎：<em>{{loginName}}</em>
                </div>
                <div class="login_btn fl" v-else>
                	<a href="login.html">登录</a>
                    <span> | </span>
                    <a href="./back/manager/adminlogin.html">管理员登录</a>
                    <span> | </span>
                    <a href="register.html">注册</a>
                </div>
            	 <div class="user_link fl" v-if="onlogin">
                    <span> | </span>
                    <a href="user_center_info.html">用户中心</a>
                    <span> | </span>
                    <a href="cart.html">我的购物车</a>
                    <span> | </span>
                    <a href="user_center_order.html">我的订单</a>
                     <span>|</span>
                     <a href="" @click.prevent="logout()">退出登录</a>
           		 </div> 
             </div>
    	</div>
    </div>
    
     <!-- 搜素框 -->
     <div class="search_bar clearfix">
     		<a href="index.html" class="logo fl"><img src="images/logo.png"></a>
         <div class="search_con fl">
             <form>
                 <input type="text" id="searchInput" class="input_text fl" name="key_words" placeholder="搜索商品"
                        autocomplete="off" @keyup="showSuggestions()"
                        @focus="showSuggestions()" @blur="hideSuggestions()" v-model="gname_search">
                 <input type="button" class="input_btn fr" value="搜索" @click="findByGname()">
             </form>
             <div class="search-container">
                 <div class="suggestions" id="suggestionsContainer"></div>
             </div>
         </div>

     		<div class="guest_cart fr">
            	<a @click="findCart()" class="cart_name fl">我的购物车</a>
                <div class="goods_count fl" id="show_count">{{goodsCount}}</div>
            </div>
     </div>

    <!-- 商品分类 -->
    <div class="navbar_con">
    	<div class="navbar">
    		<h1 class="fl">全商品分类</h1>
    		<ul class="navlist fl">
    			<li><a href="">首页</a></li>
                <li class="interval">|</li>
                <li><a href="">手机生鲜</a></li>
                <li class="interval">|</li>
                <li><a href="">抽奖</a></li>
    		</ul>
    	</div>
    </div>
    
    <!-- 导航栏 -->
    <div class="center_con clearfix">
        <div class="subnav fl" >
<!--            <div class="subnav fl" v-for="type in types">-->
            <ul v-for="(type,index) in types">
                <li><a :href="'goods.html#'+type.tno+'&'+type.tname" :class="classes[index]">{{type.tname}}</a></li>
            </ul>
        </div>
        <div class="slide fl">
            <ul class="slide_pics">
                <li><a href="" class=""><img src="images/slide.jpg" alt="幻灯片"></a></li>
                <li><a href="" class=""><img src="images/slide02.jpg" alt="幻灯片"></a></li>
                <li><a href="" class=""><img src="images/slide03.jpg" alt="幻灯片"></a></li>
                <li><a href="" class=""><img src="images/slide04.jpg" alt="幻灯片"></a></li>
            </ul>
            <div class="prev"></div>
            <div class="next"></div>
            <ul class="points"></ul>
        </div>
        <div class="adv fl">
            <a href=""><img src="images/adv01.jpg" alt="清凉一夏"></a>
            <a href=""><img src="images/adv02.jpg" alt="盛夏尝鲜"></a>
        </div>
    </div>
    <!--猜你喜欢************************************************-->
    <div class="list_model" v-if="mno!=0">
        <div class="list_title clearfix">
            <h3 class="fl" >猜你喜欢</h3>
            <div class="subtitle fl">
                <span>|</span>
                <a :href="'details.html#'+recommendGood.gno" v-for="recommendGood in recommendGoods" >{{recommendGood.gname}}</a>
                <!--                                                         "good in goods.slice(0, 4)"-->
            </div>
        </div>

        <div class="goods_con clearfix">
            <ul class="goods_list fl">
                <li v-for="recommendGood in recommendGoods" >
                    <h4><a :href="'details.html#'+recommendGood.gno">{{recommendGood.gname}}</a></h4>
                    <a :href="'details.html#'+recommendGood.gno"><img :src="'./'+recommendGood.pics"></a>
                    <div class="prize">￥ {{recommendGood.price}}</div>
                </li>
            </ul>
        </div>
    </div>

    <!-- 商品展示 -->
    <div class="list_model"  v-for="type in types">
        <div class="list_title clearfix">
            <h3 class="fl" id="model01">{{type.tname}}</h3>
            <div class="subtitle fl">
                <span>|</span>
                <a :href="'details.html#'+good.gno" v-for="good in goods" v-if="good.tno == type.tno">{{good.gname}}</a>
<!--                                                         "good in goods.slice(0, 4)"-->
            </div>
            <a :href="'goods.html#'+type.tno+'&'+type.tname" class="goods_more fr" id="fruit_more">查看更多</a>
        </div>

        <div class="goods_con clearfix">
            <div class="goods_banner fl"><img :src="type.pic"></div>
            <ul class="goods_list fl">
                <li v-for="good in goods" v-if="good.tno == type.tno">
                    <h4><a :href="'details.html#'+good.gno">{{good.gname}}</a></h4>
                    <a :href="'details.html#'+good.gno"><img :src="'./'+good.pics"></a>
                    <div class="prize">￥ {{good.price}}</div>
                </li>
            </ul>
        </div>
    </div>
</div>

    
    <!-- 版权所有 -->
    <div class="footer">
    	<div class="foot_link">
        	<a href="#">关于我们</a> <span> | </span>
            <a href="#">联系我们</a> <span> | </span>
            <a href="#">招聘广告</a> <span> | </span>
            <a href="#">友情链接</a>
        </div>
    	<p>CopyRight &copy; 2019 衡阳市源辰信息科技有限公司 All Rights Reserverd</p>
        <p>电话：0734-8355998 湘ICP备16015987号-1</p>
    </div>
    
    <!--  注意引入顺序 -->
	<script src="js/jquery-3.4.1.min.js"></script>
    <script src="js/jquery-ui.min.js"></script>
    <script src="js/slide.js"></script>
    <script src="js/vue.js"></script>
    <script src="js/axios.js"></script>
    <script src="js/qs.js"></script>

    <script>
        Vue.prototype.axios = axios;
        axios.interceptors.request.use(config => {
                const token = localStorage.getItem('token');
                if (token) {
                    config.headers.Authorization = token;
                } else {
                    config.headers.Authorization = '';
                }
                console.log(token);
                console.log(config);
                return config;
            }, error => {
                return Promise.reject(error);
            }
        );

        let begin ="http://localhost:20001/";
        let security = "freshgood-security/";
        let goods = "freshgood-goods/";
        let app = new Vue({
            el: "#yc-index",
            data: {
                classes:['fruit','seafood','meet','egg','vegetables','ice'],
                onlogin: false,
                outlogin: true,
                loginName: '匿名',
                types: {},
                goods: {},
                carts: {},
                goodsCount: 0,
                recommendGoods:{},//1111111111111111111111111111111111111
                mno:0,//1111111111111111111111111111
                gname_search: "",
                suggestions: [],
            },
            mounted:function(){
                checkLogin().then(rs=>{
                    console.log(rs.data);
                })
            },
            mounted: function () {
                //记载页面时，发送请求检查用户是否登录请求   分类查看前四条商品
                axios.all([checkLogin(), findTop()
                    // ,findRecommend()
                ])
                    .then(axios.spread((rs1, rs2
                        // , rs3
                    ) => {//rs3333333333333333333333333333
                        if(rs1.data.code === 0){
                            //说明未登录
                            this.onlogin = false;
                            this.outlogin = true;
                        }else{
                            localStorage.setItem('user', JSON.stringify(rs1.data.user));
                            this.loginName = rs1.data.user.nickName;
                            this.carts = rs1.data.cartList;
                            console.log(rs1.data)
                            this.mno=rs1.data.user.mno;
                            for (let i = 0; i < this.carts.length; i++) {
                                this.goodsCount += this.carts[i].num;
                            }
                            this.onlogin = true;
                            this.outlogin = false;
                        }
                        this.goods = rs2.data.goods;
                        this.types = rs2.data.types;
                        // this.recommendGoods=rs3.data.recommendGoods;//11111111111111111
                        }));
            },
            methods: {
                findByGname: function () {
                    // location.href = "goodsSearch.html#gname=" + this.gname_search;
                },
                search: function(){
                    location.href="login.html";
                },
                logout: function () {
                    axios(loginOut()).then(rs=>{
                        if(rs.data.code===1){
                            this.onlogin = false,
                                this.outlogin = true,
                                localStorage.removeItem("token")
                        }else{
                            alert("出现异常")
                        }
                    },

                    );
                    location.href="login.html";
                },
                findCart:function(){
                    if(this.onlogin===false){
                        alert("请先登录！");
                        location.href="login.html";
                        return ;
                    }
                    location.href="cart.html";
                },
                showSuggestions: function () {
                    var currentIndex = -1;
                    var input = document.getElementById("searchInput");
                    var suggestionsContainer = document.getElementById("suggestionsContainer");
                    var inputValue = input.value.trim().toLowerCase();

                    // 清空之前的建议
                    suggestionsContainer.innerHTML = "";

                    // 如果输入框为空，则隐藏建议框
                    if (inputValue === "") {
                        suggestionsContainer.style.display = "none";
                        return;
                    }
                    // 这里可以根据需要使用Ajax请求，从后端获取相关搜索建议数据
                    axios({
                        url: "good",
                        method: "get",
                        params: {gname: inputValue, op: "findByGname"}
                    }).then(rs => {
                        for (let i = 0; i < rs.data.searchGoodsNames.length; i++) {
                            if (!this.suggestions.includes(rs.data.searchGoodsNames[i]))
                                this.suggestions.push(rs.data.searchGoodsNames[i]);
                        }
                        var matchedSuggestions = this.suggestions.filter(function (suggestion) {
                            return suggestion.toLowerCase().includes(inputValue);
                        });

                        // 生成建议列表
                        var ul = document.createElement("ul");
                        matchedSuggestions.forEach(function (suggestion, index) {
                            var li = document.createElement("li");
                            li.innerText = suggestion;
                            li.addEventListener("mousedown", function (e) {
                                e.preventDefault();
                            });
                            //https://blog.csdn.net/caicai1171523597/article/details/86639933?app_version=5.15.4&code=app_1562916241&csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%2286639933%22%2C%22source%22%3A%22kirito823%22%7D&uLinkId=usr1mkqgl919blen&utm_source=app
                            //blur事件与click事件冲突的解决办法
                            li.addEventListener("click", function () {
                                input.value = suggestion;
                                suggestionsContainer.style.display = "none";
                                //为什么要借助data.&data,因为这是js外部加监听，实质是还是js访问，
                                // 所以得需要data.&data来帮助赋值元素给它
                                data.gname_search = input.value;
                            });

                            li.addEventListener("mouseover", function () {
                                li.classList.add("highlight");
                                currentIndex = index;
                            });

                            li.addEventListener("mouseout", function () {
                                li.classList.remove("highlight");
                                currentIndex = -1;
                            });

                            ul.appendChild(li);
                        });

                        suggestionsContainer.appendChild(ul);
                        // 如果有匹配的建议，则显示建议框
                        if (matchedSuggestions.length > 0) {
                            suggestionsContainer.style.display = "block";
                        } else {
                            suggestionsContainer.style.display = "none";
                        }
                    });


                },
                hideSuggestions:function () {
                    suggestionsContainer.style.display = "none";
                },

            }

        });
        const data = app.$data;
        //检查用户是否登录
        function checkLogin() {
            return axios.get(begin+security+"security/freshgood/loginCheck");

        }
        function loginOut() {
            return axios.get(begin+security+"security/freshgood/loginOut");
        }
        //分类查询前四条商品
        function findTop() {
            return axios.get(begin+goods+"goods/findTop");
        }

        //查询推荐商品
        function findRecommend() {//11111111111111111111111111111111111111111111
            return axios.get("good?op=findRecommend");
        }


		//获取url地址栏
    	function getQueryString(name) {
			//正则表达式
			var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
			///获取url中从问号（"?"符）开始的字符串
			var url = decodeURI(window.location.search);
			//截取？后面的字符串
			var r = url.substr(1).match(reg);
			if (r != null) {
				//decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码
				return decodeURI(r[2]);
			}
			return null;
		}
        function showBrowsingHistory() {
            var searchHistory = document.getElementById("searchHistory");
            searchHistory.style.display = "block";
        }

        var currentIndex = -1;

        function showSuggestions() {
            var input = document.getElementById("searchInput");
            var suggestionsContainer = document.getElementById("suggestionsContainer");
            var inputValue = input.value.trim().toLowerCase();

            // 清空之前的建议
            suggestionsContainer.innerHTML = "";

            // 如果输入框为空，则隐藏建议框
            if (inputValue === "") {
                suggestionsContainer.style.display = "none";
                return;
            }

            // 这里可以根据需要使用Ajax请求，从后端获取相关搜索建议数据
            // 这里仅使用硬编码的示例数据
            var suggestions = ["手机","手机1","手机2","手机3","手机4", "电视", "笔记本电脑", "音响", "耳机", "鼠标", "键盘"];

            var matchedSuggestions = suggestions.filter(function (suggestion) {
                return suggestion.toLowerCase().includes(inputValue);
            });

            // 生成建议列表
            var ul = document.createElement("ul");
            matchedSuggestions.forEach(function (suggestion, index) {
                var li = document.createElement("li");
                li.innerText = suggestion;
                li.addEventListener("click", function () {
                    input.value = suggestion;
                    suggestionsContainer.style.display = "none";
                });

                li.addEventListener("mouseover", function () {
                    li.classList.add("highlight");
                    currentIndex = index;
                });

                li.addEventListener("mouseout", function () {
                    li.classList.remove("highlight");
                    currentIndex = -1;
                });

                ul.appendChild(li);
            });

            suggestionsContainer.appendChild(ul);

            // 如果有匹配的建议，则显示建议框
            if (matchedSuggestions.length > 0) {
                suggestionsContainer.style.display = "block";
            } else {
                suggestionsContainer.style.display = "none";
            }
        }
    </script>
</body>
</html>
